package com.lzp.java.concurrent.jmm.synchronize;

/**
 * 使用对象锁--代码块形式 自定义锁对象
 */
public class SynchronizedObjectCodeBlock2 implements Runnable {
    private static SynchronizedObjectCodeBlock2 instance = new SynchronizedObjectCodeBlock2();

    // 定义两个锁对象
    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);
        t1.start();
        t2.start();
        /* 死循环等待线程结束*/
        while (t1.isAlive() || t2.isAlive()) {

        }
    }

    @Override
    public void run() {
        synchronized (lock1) {
            System.out.println("lock1部分开始，当前线程" + Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("lock1部分结束，当前线程" + Thread.currentThread().getName());
        }
        synchronized (lock2) {
            System.out.println("lock2部分开始，当前线程" + Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("lock2部分结束，当前线程" + Thread.currentThread().getName());
        }
    }
}
